package com.tanhua.server.controller;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.UserDto;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserServise;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServise userServise;

    @Autowired
    private UserInfoService userInfoService;


    /**
     * 获取验证码
     *
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody UserDto userDto) {
        //获取JSON中电话
        String phone = userDto.getPhone();
        userServise.sendSms(phone);
        return ResponseEntity.ok(null);
    }


    /**
     * 用户登录
     *
     * @param userDto
     * @return
     */
    @PostMapping("/loginVerification")
    public ResponseEntity loginUser(@RequestBody UserDto userDto) {
        //接收参数
        String phone = userDto.getPhone();
        String code = userDto.getVerificationCode();
        //调用Service查询
        UserVo result = userServise.loginUser(phone, code);
        return ResponseEntity.ok(result);
    }

    /**
     * 完善资料
     *
     * @param userInfo
     * @return
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo) {

        //1.校验token,从线程当中获取id
        Long userId = UserThreadLocal.getUserId();
        //2.保存用户信息
        userInfo.setId(userId);
        //3.调用serviceInfo添加到数据库
        userInfoService.loginRegInfo(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 上传头像
     *
     * @param headPhoto
     * @return
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity upLodHead(MultipartFile headPhoto) {

        //1.校验token,从线程当中获取id
        Long userId = UserThreadLocal.getUserId();

        //3.调用service
        try {
            userInfoService.updateHead(headPhoto, userId);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
        return ResponseEntity.ok(null);
    }

}
